package com.shjy.client.activity;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.webkit.ConsoleMessage;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.shjy.client.R;
import com.shjy.client.delegate.MainWebviewDelegate;
import com.shjy.client.util.Const;

import java.net.URL;

public class MainActivity extends AppCompatActivity {

    private Toolbar mToolbar;
    private TextView mToolbarTitleTextView;
    private TextView mBackTextView;
    private ImageView mImageView;
    private Button mButton;

    private TextView menuHome;
    private TextView menuOrder;
    private TextView menuMe;
    private WebView mWebView;

    private long mCurrentTimeMillis;
    private int mCurrentMenu;

    private Handler mHandler;

    private boolean notReload;

    public final static int WHAT_TO_DETAIL = 9;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // layout
        setContentView(R.layout.activity_main);

        // 初始化 Handler
        initHandler();

        // 初始化 Toolbar
        initToolbar();

        // 初始化 Webview
        initWebview();

        // 初始化 底部导航栏
        initBottomNavigationBar();

        // 权限设定
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
            builder.setMessage("请授予\"上海交运\"定位权限").setNegativeButton("禁止", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                }
            }).setPositiveButton("允许", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
                    }
                }
            }).create().show();
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();

        if (!notReload) {
            // reload
            mWebView.reload();
        } else {
            notReload = false;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == resultCode) {
            String menuIndex = data.getStringExtra("menuIndex");
            if (!TextUtils.isEmpty(menuIndex)) {
                if (TextUtils.equals("0", menuIndex)) {
                    notReload = true;
                    menuHome.performClick();
                }
            }
        }
    }

    @Override
    public void onBackPressed() {

        String[] urls = new String[]{Const.URL_HOME, Const.URL_ORDERLIST, Const.URL_ME};
        boolean canGoBack = !mWebView.getUrl().equals(urls[mCurrentMenu]) && mWebView.canGoBack();

        if (canGoBack) {
            mWebView.goBack();
        } else {
            if (System.currentTimeMillis() - mCurrentTimeMillis > 2000) {
                Toast.makeText(getApplicationContext(), "再点一次退出程序", Toast.LENGTH_SHORT).show();
                mCurrentTimeMillis = System.currentTimeMillis();
            } else {
                super.onBackPressed();
            }
        }
    }

    private void initHandler() {

        mHandler = new Handler() {
            public void handleMessage(Message msg) {
                // 我的订单
                if (msg.what == WHAT_TO_DETAIL) {
                    Intent intent = new Intent(MainActivity.this, DetailActivity.class);
                    intent.putExtra("url", (String) msg.obj);
                    intent.putExtra("currentMenu", mCurrentMenu);
                    startActivityForResult(intent, WHAT_TO_DETAIL);
                }
            }
        };
    }

    private void initToolbar() {

        // 导航栏标题
        setTitle("下单选车");

        // 导航栏设定
        mToolbar = (Toolbar) findViewById(R.id.toolbar);

        // 导航栏标题
        mToolbarTitleTextView = (TextView) mToolbar.findViewById(R.id.titleTextView);
        mToolbarTitleTextView.setText("");

        // 设定导航栏返回图标的大小
        DisplayMetrics outMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(outMetrics);

        float density = outMetrics.density;
        int right = (int) (20 * density);
        int bottom = right;
        Rect bounds = new Rect(0, 0, right, bottom);

        // 导航栏返回
        mBackTextView = (TextView) mToolbar.findViewById(R.id.backTextView);
        Drawable[] drawables = mBackTextView.getCompoundDrawables();
        Drawable drawable = drawables[0];
        drawable.setBounds(bounds);
        mBackTextView.setCompoundDrawables(drawable, null, null, null);
        mBackTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });

        // logo
        mImageView = (ImageView) mToolbar.findViewById(R.id.logoImageView);
        mImageView.setVisibility(View.VISIBLE);

        // 提交按钮
        mButton = (Button) mToolbar.findViewById(R.id.button);
        mButton.setVisibility(View.INVISIBLE);
        mButton.setEnabled(false);
        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mWebView.loadUrl("javascript:save()");
            }
        });

        setSupportActionBar(mToolbar);
    }

    private void initWebview() {

        mWebView = (WebView) findViewById(R.id.webview);

        // 优先使用缓存
        //mWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setDefaultTextEncodingName("UTF-8");
        mWebView.getSettings().setDomStorageEnabled(true);

        mWebView.setWebChromeClient(new MainWebChromeClient());
        mWebView.setWebViewClient(new MainWebViewClient());
        mWebView.addJavascriptInterface(new MainWebviewDelegate(this, mHandler), "delegate");

        mWebView.loadUrl(Const.URL_HOME);
    }

    private void initBottomNavigationBar() {

        menuHome = (TextView) findViewById(R.id.menu_home);
        menuOrder = (TextView) findViewById(R.id.menu_order);
        menuMe = (TextView) findViewById(R.id.menu_me);

        resetBottomNavigationBar();

        // 首页
        menuHome.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                mWebView.loadUrl(Const.URL_HOME);

                // 重新设定底部导航栏
                resetBottomNavigationBar();
                menuHome.setTextColor(getResources().getColor(R.color.colorBottomMenuSelected));
                Drawable[] drawables = menuHome.getCompoundDrawables();
                Drawable drawable = getResources().getDrawable(R.drawable.i_home_selected);
                drawable.setBounds(drawables[1].getBounds());
                menuHome.setCompoundDrawables(null, drawable, null, null);

                mCurrentMenu = 0;
            }
        });
        // 订单
        menuOrder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                mWebView.loadUrl(Const.URL_ORDERLIST);

                // 重新设定底部导航栏
                resetBottomNavigationBar();
                menuOrder.setTextColor(getResources().getColor(R.color.colorBottomMenuSelected));
                Drawable[] drawables = menuOrder.getCompoundDrawables();
                Drawable drawable = getResources().getDrawable(R.drawable.i_order_selected);
                drawable.setBounds(drawables[1].getBounds());
                menuOrder.setCompoundDrawables(null, drawable, null, null);

                mCurrentMenu = 1;
            }
        });

        // 我的
        menuMe.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                mWebView.loadUrl(Const.URL_ME);

                // 重新设定底部导航栏
                resetBottomNavigationBar();
                menuMe.setTextColor(getResources().getColor(R.color.colorBottomMenuSelected));
                Drawable[] drawables = menuMe.getCompoundDrawables();
                Drawable drawable = getResources().getDrawable(R.drawable.i_me_selected);
                drawable.setBounds(drawables[1].getBounds());
                menuMe.setCompoundDrawables(null, drawable, null, null);

                mCurrentMenu = 2;
            }
        });

        menuHome.setTextColor(getResources().getColor(R.color.colorBottomMenuSelected));
        Drawable[] drawables = menuHome.getCompoundDrawables();
        Drawable drawable = getResources().getDrawable(R.drawable.i_home_selected);
        drawable.setBounds(drawables[1].getBounds());
        menuHome.setCompoundDrawables(null, drawable, null, null);
    }

    private void resetBottomNavigationBar() {

        DisplayMetrics outMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(outMetrics);
        float density = outMetrics.density;
        int right = (int) (25 * density);
        int bottom = right;

        int colorNormal = getResources().getColor(R.color.colorBottomMenuNormal);
        Rect bounds = new Rect(0, 0, right, bottom);

        menuHome.setTextColor(colorNormal);
        Drawable[] drawables = menuHome.getCompoundDrawables();
        Drawable drawable = getResources().getDrawable(R.drawable.i_home);
        drawable.setBounds(bounds);
        menuHome.setCompoundDrawables(null, drawable, null, null);

        menuOrder.setTextColor(colorNormal);
        drawables = menuHome.getCompoundDrawables();
        drawable = getResources().getDrawable(R.drawable.i_order);
        drawable.setBounds(bounds);
        menuOrder.setCompoundDrawables(null, drawable, null, null);

        menuMe.setTextColor(colorNormal);
        drawables = menuHome.getCompoundDrawables();
        drawable = getResources().getDrawable(R.drawable.i_me);
        drawable.setBounds(bounds);
        menuMe.setCompoundDrawables(null, drawable, null, null);

        mCurrentMenu = 0;
    }

    class MainWebChromeClient extends WebChromeClient {

        @Override
        public void onReceivedTitle(WebView view, String title) {
            mToolbarTitleTextView.setText(title);
        }

        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
            final AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
            builder.setTitle(null).setMessage(message).setPositiveButton("确定", null);
            builder.setCancelable(false);
            AlertDialog dialog = builder.create();
            dialog.show();
            result.confirm();
            return true;
        }

        @Override
        public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {
            return super.onJsConfirm(view, url, message, result);
        }

        @Override
        public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
            return super.onConsoleMessage(consoleMessage);
        }
    }

    class MainWebViewClient extends WebViewClient {
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            // 拦截url
            if (url.indexOf("login.html") != -1) {

                SharedPreferences sharedPreferences = getSharedPreferences("Login", Context.MODE_PRIVATE);
                boolean result = sharedPreferences.getBoolean("LoginSuccess", false);

                if (result) {

                    if (mCurrentMenu == 0) {
                        menuHome.performClick();
                    } else if (mCurrentMenu == 1) {
                        menuOrder.performClick();
                    } else if (mCurrentMenu == 2) {
                        menuMe.performClick();
                    }
                } else {

                    // 跳转到LoginActivity
                    Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                    startActivity(intent);

                    // 停止加载
                    mWebView.stopLoading();
                }

                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.remove("LoginSuccess");
                editor.commit();
            } else if (!(TextUtils.equals(url, Const.URL_HOME) && mCurrentMenu == 0) &&
                    !(TextUtils.equals(url, Const.URL_ORDERLIST) && mCurrentMenu == 1) &&
                    !(TextUtils.equals(url, Const.URL_ME) && mCurrentMenu == 2)) {

                // 跳转到DetailActivity
                Message message = new Message();
                message.what = WHAT_TO_DETAIL;
                message.obj = url;

                mHandler.sendMessage(message);

                // 停止加载
                mWebView.stopLoading();
            } else if (url.indexOf("index.html") != -1) {

                if (mCurrentMenu == 0) {
                    menuHome.performClick();
                } else if (mCurrentMenu == 1) {
                    menuOrder.performClick();
                } else if (mCurrentMenu == 2) {
                    menuMe.performClick();
                }
            } else {

                if (TextUtils.equals(url, Const.URL_HOME) && mCurrentMenu == 0) {

                    mToolbar.setVisibility(View.VISIBLE);
                    mBackTextView.setVisibility(View.GONE);
                } else if (TextUtils.equals(url, Const.URL_ORDERLIST) && mCurrentMenu == 1) {
                    mToolbar.setVisibility(View.GONE);
                    mBackTextView.setVisibility(View.GONE);
                }

                super.onPageStarted(view, url, favicon);
            }
        }
    }
}
